<?php

namespace App\Util;

/**
 * Created by PhpStorm.
 * User: eric
 * Date: 2016/10/12
 * Time: 10:59
 */
class Helper
{

    /**
     * 阶乘
     * @param $n
     * @return float|int
     */
    public static function factorial($n)
    {
        //array_product 计算并返回数组的乘积
        //range 创建一个包含指定范围的元素的数组
        return array_product(range(1, $n));
    }


    /**
     * 排列数
     * @param $n
     * @param $m
     * @return float|int
     */
    public static function permutation($n, $m)
    {
        return self::factorial($n) / self::factorial($n - $m);
    }

    /**
     * 求组合数
     * @param $n
     * @param $m
     * @return float
     */
    public static function combination($n, $m)
    {
        if (($n - $m) <= 0) {
            return 1;
        }
        return self::permutation($n, $m) / self::factorial($m);
    }

    /**
     * 排列结果
     * @param $a
     * @param $m
     * @return array
     */
    public static function arrangement($a, $m)
    {
        $r = array();
        $n = count($a);
        if ($m <= 0 || $m > $n) {
            return $r;
        }
        for ($i = 0; $i < $n; $i++) {
            $b = $a;
            //从数组中移除选定的元素，并用新元素取代它。该函数也将返回包含被移除元素的数组
            $t = array_splice($b, $i, 1);
            if ($m == 1) {
                $r[] = $t;
            } else {
                $c = self::arrangement($b, $m - 1);
                foreach ($c as $v) {
                    $r[] = array_merge($t, $v);
                }
            }
        }

        return $r;
    }


    /**
     * 组合结果
     * @param $a
     * @param $m
     * @return array 返回组合明细
     */
    public static function combinationList($a, $m)
    {
        $r = array();

        $n = count($a);
        if ($m <= 0 || $m > $n) {
            return $r;
        }

        for ($i = 0; $i < $n; $i++) {
            $t = array($a[$i]);
            if ($m == 1) {
                $r[] = $t;
            } else {
                //array_slice() 函数在数组中根据条件取出一段值，并返回。
                //array_slice(array,start,length,preserve)
                $b = array_slice($a, $i + 1);
                $c = self::combinationList($b, $m - 1);
                foreach ($c as $v) {
                    //array_merge() 函数把一个或多个数组合并为一个数组
                    $r[] = array_merge($t, $v);
                }
            }
        }
        return $r;
    }



    /**
     * @return bool
     */
    public static function inWechat()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }


    /**
     * 判断是否为Json字符串
     * @param $string
     * @return bool
     */
    public static function json($string)
    {
        if (is_array($string)) {
            return false;
        }
        @json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }



    /**
     * 去掉width 和 height标签
     * @param $content
     * @return mixed
     */
    public static function clearImgWidthHeight($content)
    {
        preg_match_all('/<[img|IMG].*?src=[\'|"](.*?(?:[\.gif|\.jpg|\.png\.bmp\w_\d]))[\'|"].*?[\/]?>/', $content, $images);
        if (!empty($images)) {
            foreach ($images[0] as $index => $value) {
                $new_img = preg_replace('/(width|height)="\d*"\s/', "", $images[0][$index]);
                $content = str_replace($images[0][$index], $new_img, $content);
            }
        }
        return $content;
    }



    /**
     * 检测是否是一个日期格式
     *
     * @param string 2012-03-01
     * @return bool
     */
    public static function vdate($date)
    {
        if (preg_match('/[\d]{4}-[\d]{2}-[\d]{2}/', $date) && $date != '0000-00-00') {
            return True;
        }
        return False;
    }

    /**
     * 单位转换,分转为元
     * @param $money
     * @return mixed
     */
    public static function amount($money)
    {
        return sprintf("%.2f", round($money, 2));
    }

    /**
     * 单位转换,分转为元
     * @param $money
     * @return mixed
     */
    public static function centToYuan($money)
    {
        return sprintf("%.2f",round($money / 100, 2));
    }

    /**
     * 单位转换,元转为分
     * @param $money
     * @return mixed
     */
    public static function yuanToCent($money)
    {
        return intval($money * 100);
    }

    public static function checkSubstrs($substrs, $text)
    {
        foreach ($substrs as $substr) {
            if (false !== strpos($text, $substr)) {
                return true;
            }
            return false;
        }
    }

    /**
     * 判断是否属于手机环境
     * @return bool
     */
    public static function inMobile()
    {

        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }

        $useragent               = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $useragent_commentsblock = preg_match('|\(.*?\)|', $useragent, $matches) > 0 ? $matches[0] : '';

        $mobile_os_list    = array('Google Wireless Transcoder', 'Windows CE', 'WindowsCE', 'Symbian', 'Android', 'armv6l', 'armv5', 'Mobile', 'CentOS', 'mowser', 'AvantGo', 'Opera Mobi', 'J2ME/MIDP', 'Smartphone', 'Go.Web', 'Palm', 'iPAQ');
        $mobile_token_list = array('Profile/MIDP', 'Configuration/CLDC-', '160×160', '176×220', '240×240', '240×320', '320×240', 'UP.Browser', 'UP.Link', 'SymbianOS', 'PalmOS', 'PocketPC', 'SonyEricsson', 'Nokia', 'BlackBerry', 'Vodafone', 'BenQ', 'Novarra-Vision', 'Iris', 'NetFront', 'HTC_', 'Xda_', 'SAMSUNG-SGH', 'Wapaka', 'DoCoMo', 'iPhone', 'iPod');

        $found_mobile = self::checkSubstrs($mobile_os_list, $useragent_commentsblock) || self::checkSubstrs($mobile_token_list, $useragent);

        if ($found_mobile) {
            return true;
        } else {
            return false;
        }

    }




    /**
     * @param $url
     * @param $page
     * @param $count
     * @param $records
     * @return string
     *
     */
    public static function page($url, $page, $count, $records)
    {
        if (!$records) {
            return '';
        }
        if (strpos($url, '?') === false) {
            $url .= '?';
        } else {
            $url .= '&amp;';
        }
        $return = '<div class="page"><div class="page1"><div id="pager" class="pagebar"><span class="f_l f6" style="margin-right:10px;">总计 <b> ' . $records . ' </b>  个记录</span>';
        $return .= ($page == 1) ? '' : '<a href="' . $url . 'page=1">首页</a><a href="' . $url . 'page=' . ($page - 1) . '">上一页</a>';
        $s      = ($page - 10 < 1) ? 1 : ($page - 10);
        $e      = ($page + 9 > $count) ? $count : ($page + 9);
        if ($count > 1) {
            for ($s; $s <= $e; $s++) {
                if ($s != $page) {
                    $return .= '<a href="' . $url . 'page=' . $s . '">[' . $s . ']</a>';
                } else {
                    $return .= '<span class="page_now">' . $s . '</span>';
                }
            }
        }
        $return .= ($page >= $count || $count == 1) ? '' : '<a href="' . $url . 'page=' . ($page + 1) . '" class="next">下一页</a><a href="' . $url . 'page=' . $count . '">尾页</a>';
        $return .= '</div></div></div>';
        return ($return);
    }

    /**
     * @param       $data
     * @param array $allow
     * @param array $deny
     * @return mixed
     */
    public static function arrayField($data, $allow = array(), $deny = array())
    {
        if (!empty($data)) {
            foreach ($data as $key => &$record) {
                if (is_array($record)) {
                    foreach ($record as $tkey => $val) {
                        if (count($allow) && !in_array($tkey, $allow)) {
                            unset($record[$tkey]);
                        }
                        if (count($deny) && in_array($tkey, $deny)) {
                            unset($record[$tkey]);
                        }
                    }
                } else {
                    if (count($allow) && !in_array($key, $allow)) {
                        unset($data[$key]);
                    }
                    if (count($deny) && in_array($key, $deny)) {
                        unset($data[$key]);
                    }
                }
            }
        }
        return $data;
    }


    /**
     * 返回key=>val映射
     * @param $data
     * @param $key
     * @param $val
     * @return array
     */
    public static function arrayMapByKey($data, $key = 'id', $val = '')
    {
        $result = array();
        if (!empty($data)) {
            foreach ($data as $record) {
                if (empty($val)) {
                    $result[$record[$key]] = $record;
                } elseif (isset($record[$val])) {
                    $result[$record[$key]] = $record[$val];
                }
            }
        }
        return $result;
    }



    /**
     * 从一个二维数组中返回指定键的所有值
     * @param array $arr
     * @param string $col
     * @param int $needUnique
     * @return array
     */
    public static function array_col_values(&$arr, $col, $needUnique = 0)
    {
        $ret = array();
        foreach ($arr as $row) {
            if (isset($row[$col])) {
                $ret[] = $row[$col];
            }
        }
        if ($needUnique == 1) {
            return array_values(array_unique($ret));
        } else {
            return $ret;
        }
    }



    /**
     * 将无限分类进行分级别,设定lv值
     * @param $primary
     * @param $arr
     * @param array $arr2
     * @param int $perId
     * @param int $lv
     */
    public static function rLevel($primary, $arr, &$arr2 = array(), $perId = 0, $lv = 0)
    {
        if (!empty($arr)) {
            foreach ($arr as $value) {
                if (isset($value['parent_id']) && $value['parent_id'] == $perId) {
                    $value['lv']            = $lv;
                    $arr2[$value[$primary]] = $value;
                    $lv++;
                    self::rLevel($primary, $arr, $arr2, $value[$primary], $lv--);
                }
            }
        }
    }

    /**
     * 返回订单号
     * @param int $len
     * @param int $type 订单号类型 1 商城订单 2 商城主订单
     * @return string
     */
    public static function sn($len = 17, $type = 1)
    {
        $salt = self::random($len - 15, 1);
        $year = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        return $year[intval(date('Y')) - 2020] . $year[$type - 1] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . $salt;
    }

    /**
     * @param     $length
     * @param int $numeric
     * @return string
     */
    public static function random($length, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
        $seed = base_convert(md5(print_r($_SERVER, 1) . microtime()), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        $hash = '';
        $max  = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed[mt_rand(0, $max)];
        }
        return $hash;
    }



    /**
     * +----------------------------------------------------------
     * 字符串截取，UTF8版本 2个英文或者数字算做一个汉字宽度,专门用于前台标题截取
     * +----------------------------------------------------------
     * @static
     * @access public
     * +----------------------------------------------------------
     * @param string $str 需要截取的字符串
     * @param string $len 截取长度
     * @param string $suffix 截断显示字符
     * @param string $start 开始位置
     * +----------------------------------------------------------
     * @return string
     * +----------------------------------------------------------
     */
    public static function cutword($str, $len, $suffix = '', $start = 0)
    {

        $osLen = mb_strlen($str);

        $string     = mb_substr($str, $start, $len, 'utf8');
        $sLen       = mb_strlen($string, 'utf8');
        $bLen       = strlen($string);
        $sCharCount = (3 * $sLen - $bLen) / 2;

        if ($osLen <= $sCharCount + $len) {
            $arr = preg_split('/(?<!^)(?!$)/u', mb_substr($str, $len + 1, $osLen, 'utf8'));
        } else {
            $arr = preg_split('/(?<!^)(?!$)/u', mb_substr($str, $len, $sCharCount, 'utf8'));
        }

        foreach ($arr as $value) {
            if (ord($value) < 128 && ord($value) > 0) {
                $sCharCount = $sCharCount - 1;
            } else {
                $sCharCount = $sCharCount - 2;
            }
            if ($sCharCount <= 0) {
                break;
            }
            $string .= $value;
        }

        if ($osLen > $len) {
            $string .= $suffix;
        }

        return $string;

    }

    /**
     * +----------------------------------------------------------
     * 字符串截取，支持中文和其他编码
     * +----------------------------------------------------------
     * @static
     * @access public
     * +----------------------------------------------------------
     * @param string $str 需要转换的字符串
     * @param string $start 开始位置
     * @param string $length 截取长度
     * @param string $charset 编码格式
     * @param string $suffix 截断显示字符
     * +----------------------------------------------------------
     * @return string
     * +----------------------------------------------------------
     */
    public static function cutstr($str, $start = 0, $length, $suffix = '', $charset = 'UTF-8')
    {
        if ($suffix && mb_strlen($str, $charset) > $length) {
            return mb_substr($str, $start, $length, $charset) . $suffix;
        } else {
            return mb_substr($str, $start, $length, $charset);
        }
    }
    /*
     *  条形码生成
     *  Author	David S. Tufts
     *  Company	davidscotttufts.com
     *
     *  Date:	05/25/2003
     *  Usage:	<img src="/barcode.php?text=testing" alt="testing" />
     */
    // For demonstration purposes, get pararameters that are passed in through $_GET or set to the default value
    // $filepath = (isset($_GET["filepath"])?$_GET["filepath"]:"");
    // $text = (isset($_GET["text"])?$_GET["text"]:"0");
    // $size = (isset($_GET["size"])?$_GET["size"]:"20");
    // $orientation = (isset($_GET["orientation"])?$_GET["orientation"]:"horizontal");
    // $code_type = (isset($_GET["codetype"])?$_GET["codetype"]:"code128");
    // $print = (isset($_GET["print"])&&$_GET["print"]=='true'?true:false);
    // $sizefactor = (isset($_GET["sizefactor"])?$_GET["sizefactor"]:"1");
    // This function call can be copied into your project and can be made from anywhere in your code
    // barcode( $filepath, $text, $size, $orientation, $code_type, $print, $sizefactor );

    function barcode($filepath = "", $text = "0", $size = "20", $orientation = "horizontal", $code_type = "code128", $print = false, $SizeFactor = 1)
    {
        $code_string = "";
        // Translate the $text into barcode the correct $code_type
        if (in_array(strtolower($code_type), array("code128", "code128b"))) {
            $chksum = 104;
            // Must not change order of array elements as the checksum depends on the array's key to validate final code
            $code_array  = array(" " => "212222", "!" => "222122", "\"" => "222221", "#" => "121223", "$" => "121322", "%" => "131222", "&" => "122213", "'" => "122312", "(" => "132212", ")" => "221213", "*" => "221312", "+" => "231212", "," => "112232", "-" => "122132", "." => "122231", "/" => "113222", "0" => "123122", "1" => "123221", "2" => "223211", "3" => "221132", "4" => "221231", "5" => "213212", "6" => "223112", "7" => "312131", "8" => "311222", "9" => "321122", ":" => "321221", ";" => "312212", "<" => "322112", "=" => "322211", ">" => "212123", "?" => "212321", "@" => "232121", "A" => "111323", "B" => "131123", "C" => "131321", "D" => "112313", "E" => "132113", "F" => "132311", "G" => "211313", "H" => "231113", "I" => "231311", "J" => "112133", "K" => "112331", "L" => "132131", "M" => "113123", "N" => "113321", "O" => "133121", "P" => "313121", "Q" => "211331", "R" => "231131", "S" => "213113", "T" => "213311", "U" => "213131", "V" => "311123", "W" => "311321", "X" => "331121", "Y" => "312113", "Z" => "312311", "[" => "332111", "\\" => "314111", "]" => "221411", "^" => "431111", "_" => "111224", "\`" => "111422", "a" => "121124", "b" => "121421", "c" => "141122", "d" => "141221", "e" => "112214", "f" => "112412", "g" => "122114", "h" => "122411", "i" => "142112", "j" => "142211", "k" => "241211", "l" => "221114", "m" => "413111", "n" => "241112", "o" => "134111", "p" => "111242", "q" => "121142", "r" => "121241", "s" => "114212", "t" => "124112", "u" => "124211", "v" => "411212", "w" => "421112", "x" => "421211", "y" => "212141", "z" => "214121", "{" => "412121", "|" => "111143", "}" => "111341", "~" => "131141", "DEL" => "114113", "FNC 3" => "114311", "FNC 2" => "411113", "SHIFT" => "411311", "CODE C" => "113141", "FNC 4" => "114131", "CODE A" => "311141", "FNC 1" => "411131", "Start A" => "211412", "Start B" => "211214", "Start C" => "211232", "Stop" => "2331112");
            $code_keys   = array_keys($code_array);
            $code_values = array_flip($code_keys);
            for ($X = 1; $X <= strlen($text); $X++) {
                $activeKey   = substr($text, ($X - 1), 1);
                $code_string .= $code_array[$activeKey];
                $chksum      = ($chksum + ($code_values[$activeKey] * $X));
            }
            $code_string .= $code_array[$code_keys[($chksum - (intval($chksum / 103) * 103))]];
            $code_string = "211214" . $code_string . "2331112";
        } elseif (strtolower($code_type) == "code128a") {
            $chksum = 103;
            $text   = strtoupper($text); // Code 128A doesn't support lower case
            // Must not change order of array elements as the checksum depends on the array's key to validate final code
            $code_array  = array(" " => "212222", "!" => "222122", "\"" => "222221", "#" => "121223", "$" => "121322", "%" => "131222", "&" => "122213", "'" => "122312", "(" => "132212", ")" => "221213", "*" => "221312", "+" => "231212", "," => "112232", "-" => "122132", "." => "122231", "/" => "113222", "0" => "123122", "1" => "123221", "2" => "223211", "3" => "221132", "4" => "221231", "5" => "213212", "6" => "223112", "7" => "312131", "8" => "311222", "9" => "321122", ":" => "321221", ";" => "312212", "<" => "322112", "=" => "322211", ">" => "212123", "?" => "212321", "@" => "232121", "A" => "111323", "B" => "131123", "C" => "131321", "D" => "112313", "E" => "132113", "F" => "132311", "G" => "211313", "H" => "231113", "I" => "231311", "J" => "112133", "K" => "112331", "L" => "132131", "M" => "113123", "N" => "113321", "O" => "133121", "P" => "313121", "Q" => "211331", "R" => "231131", "S" => "213113", "T" => "213311", "U" => "213131", "V" => "311123", "W" => "311321", "X" => "331121", "Y" => "312113", "Z" => "312311", "[" => "332111", "\\" => "314111", "]" => "221411", "^" => "431111", "_" => "111224", "NUL" => "111422", "SOH" => "121124", "STX" => "121421", "ETX" => "141122", "EOT" => "141221", "ENQ" => "112214", "ACK" => "112412", "BEL" => "122114", "BS" => "122411", "HT" => "142112", "LF" => "142211", "VT" => "241211", "FF" => "221114", "CR" => "413111", "SO" => "241112", "SI" => "134111", "DLE" => "111242", "DC1" => "121142", "DC2" => "121241", "DC3" => "114212", "DC4" => "124112", "NAK" => "124211", "SYN" => "411212", "ETB" => "421112", "CAN" => "421211", "EM" => "212141", "SUB" => "214121", "ESC" => "412121", "FS" => "111143", "GS" => "111341", "RS" => "131141", "US" => "114113", "FNC 3" => "114311", "FNC 2" => "411113", "SHIFT" => "411311", "CODE C" => "113141", "CODE B" => "114131", "FNC 4" => "311141", "FNC 1" => "411131", "Start A" => "211412", "Start B" => "211214", "Start C" => "211232", "Stop" => "2331112");
            $code_keys   = array_keys($code_array);
            $code_values = array_flip($code_keys);
            for ($X = 1; $X <= strlen($text); $X++) {
                $activeKey   = substr($text, ($X - 1), 1);
                $code_string .= $code_array[$activeKey];
                $chksum      = ($chksum + ($code_values[$activeKey] * $X));
            }
            $code_string .= $code_array[$code_keys[($chksum - (intval($chksum / 103) * 103))]];
            $code_string = "211412" . $code_string . "2331112";
        } elseif (strtolower($code_type) == "code39") {
            $code_array = array("0" => "111221211", "1" => "211211112", "2" => "112211112", "3" => "212211111", "4" => "111221112", "5" => "211221111", "6" => "112221111", "7" => "111211212", "8" => "211211211", "9" => "112211211", "A" => "211112112", "B" => "112112112", "C" => "212112111", "D" => "111122112", "E" => "211122111", "F" => "112122111", "G" => "111112212", "H" => "211112211", "I" => "112112211", "J" => "111122211", "K" => "211111122", "L" => "112111122", "M" => "212111121", "N" => "111121122", "O" => "211121121", "P" => "112121121", "Q" => "111111222", "R" => "211111221", "S" => "112111221", "T" => "111121221", "U" => "221111112", "V" => "122111112", "W" => "222111111", "X" => "121121112", "Y" => "221121111", "Z" => "122121111", "-" => "121111212", "." => "221111211", " " => "122111211", "$" => "121212111", "/" => "121211121", "+" => "121112121", "%" => "111212121", "*" => "121121211");
            // Convert to uppercase
            $upper_text = strtoupper($text);
            for ($X = 1; $X <= strlen($upper_text); $X++) {
                $code_string .= $code_array[substr($upper_text, ($X - 1), 1)] . "1";
            }
            $code_string = "1211212111" . $code_string . "121121211";
        } elseif (strtolower($code_type) == "code25") {
            $code_array1 = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
            $code_array2 = array("3-1-1-1-3", "1-3-1-1-3", "3-3-1-1-1", "1-1-3-1-3", "3-1-3-1-1", "1-3-3-1-1", "1-1-1-3-3", "3-1-1-3-1", "1-3-1-3-1", "1-1-3-3-1");
            for ($X = 1; $X <= strlen($text); $X++) {
                for ($Y = 0; $Y < count($code_array1); $Y++) {
                    if (substr($text, ($X - 1), 1) == $code_array1[$Y])
                        $temp[$X] = $code_array2[$Y];
                }
            }
            for ($X = 1; $X <= strlen($text); $X += 2) {
                if (isset($temp[$X]) && isset($temp[($X + 1)])) {
                    $temp1 = explode("-", $temp[$X]);
                    $temp2 = explode("-", $temp[($X + 1)]);
                    for ($Y = 0; $Y < count($temp1); $Y++)
                        $code_string .= $temp1[$Y] . $temp2[$Y];
                }
            }
            $code_string = "1111" . $code_string . "311";
        } elseif (strtolower($code_type) == "codabar") {
            $code_array1 = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "$", ":", "/", ".", "+", "A", "B", "C", "D");
            $code_array2 = array("1111221", "1112112", "2211111", "1121121", "2111121", "1211112", "1211211", "1221111", "2112111", "1111122", "1112211", "1122111", "2111212", "2121112", "2121211", "1121212", "1122121", "1212112", "1112122", "1112221");
            // Convert to uppercase
            $upper_text = strtoupper($text);
            for ($X = 1; $X <= strlen($upper_text); $X++) {
                for ($Y = 0; $Y < count($code_array1); $Y++) {
                    if (substr($upper_text, ($X - 1), 1) == $code_array1[$Y])
                        $code_string .= $code_array2[$Y] . "1";
                }
            }
            $code_string = "11221211" . $code_string . "1122121";
        }
        // Pad the edges of the barcode
        $code_length = 20;
        if ($print) {
            $text_height = 30;
        } else {
            $text_height = 0;
        }

        for ($i = 1; $i <= strlen($code_string); $i++) {
            $code_length = $code_length + (integer)(substr($code_string, ($i - 1), 1));
        }
        if (strtolower($orientation) == "horizontal") {
            $img_width  = $code_length * $SizeFactor;
            $img_height = $size;
        } else {
            $img_width  = $size;
            $img_height = $code_length * $SizeFactor;
        }
        $image = imagecreate($img_width, $img_height + $text_height);
        $black = imagecolorallocate($image, 0, 0, 0);
        $white = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $white);
        if ($print) {
            imagestring($image, 5, 31, $img_height, $text, $black);
        }
        $location = 10;
        for ($position = 1; $position <= strlen($code_string); $position++) {
            $cur_size = $location + (substr($code_string, ($position - 1), 1));
            if (strtolower($orientation) == "horizontal")
                imagefilledrectangle($image, $location * $SizeFactor, 0, $cur_size * $SizeFactor, $img_height, ($position % 2 == 0 ? $white : $black));
            else
                imagefilledrectangle($image, 0, $location * $SizeFactor, $img_width, $cur_size * $SizeFactor, ($position % 2 == 0 ? $white : $black));
            $location = $cur_size;
        }

        // Draw barcode to the screen or save in a file
        if ($filepath == "") {
            header('Content-type: image/png');
            imagepng($image);
            imagedestroy($image);
        } else {
            imagepng($image, $filepath);
            imagedestroy($image);
        }
    }

    /**
     * 获取内容中的第一个链接
     * @param $content
     * @return bool
     */
    public static function getUrl($content)
    {
        preg_match('/(http[s]?:[\/]{2}[a-z\d-]+[.]{1}[a-z\d\-]+[.]{1}[a-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d\-\_\.\~\!\*\(\)\;\:\@\&\=\+\$\,\/\?\#\[\]]*)/', $content, $match);
        if (isset($match[1])) {
            if (self::isUrl($match[1])) {
                return $match[1];
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * php 获取短链接对应的长链接
     * @param $url
     * @return bool|string
     */
    public static function getRealUrl($url)
    {

        $redirect_url = null;

        $url_parts = @parse_url($url);

        if (!$url_parts) {
            return false;
        }

        if (!isset($url_parts['host'])) {
            return false; //can't process relative URLs
        }

        if (!isset($url_parts['path'])) {
            $url_parts['path'] = '/';
        }

        $sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);

        if (!$sock) {
            return false;
        }

        $request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?' . $url_parts['query'] : '') . " HTTP/1.1\r\n";
        $request .= 'Host: ' . $url_parts['host'] . "\r\n";
        $request .= "Connection: Close\r\n\r\n";

        fwrite($sock, $request);

        $response = '';

        while (!feof($sock)) {
            $response .= fread($sock, 8192);
        }

        fclose($sock);

        if (preg_match('/^Location: (.+?)$/m', $response, $matches)) {
            if (substr($matches[1], 0, 1) == "/") {
                return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
            } else {
                return trim($matches[1]);
            }
        } else {
            return false;
        }

    }

    /**
     * 检查是否是一个合格的 5-15 用户名字符串
     * @param $username
     * @return bool
     */
    function isUserName($username)
    {
        $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
        $len      = mb_strlen($username);
        if ($len > 15 || $len < 2 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) {
            return False;
        }
        return True;
    }

    /**
     * 检测一个变量是否为空
     * @param $value
     * @return bool
     */
    public static function isEmpty($value)
    {
        return (empty($value) || $value == "");
    }

    /**
     * 是否包含空白、控制字符
     * @param $value
     * @return mixed
     */
    public static function isSpace($value)
    {
        return preg_match('/[\s\a\f\n\e\0\r\t\x0B]/is', $value);
    }


    /**
     * email地址合法性检测
     * @param $value
     * @return mixed
     */
    public static function isEmail($value)
    {
        return preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $value);
        //return preg_match ( '/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/', $value )
    }

    /**
     * URL地址合法性检测
     * @param $value
     * @return mixed
     */
    public static function isUrl($value)
    {
        return preg_match("/^http[s]?:\/\/[\w]+\.[\w]+[\S]*/", $value);
    }

    /**
     * 是否是一个合法域名
     * @param $str
     * @return mixed
     */
    public static function isDomainName($str)
    {
        return preg_match("/^[a-z0-9]([a-z0-9-]+\.){1,4}[a-z]{2,5}$/i", $str);
    }

    /**
     * 检测IP地址是否合法
     * @param $ip
     * @return mixed
     */
    public static function isIpAddr($ip)
    {
        return preg_match("/^[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}$/", $ip);
    }

    /**
     * 邮编合法性检测
     * @param $value
     * @return bool
     */
    public static function isPostalCode($value)
    {
        return (is_numeric($value) && (strlen($value) == 6));
    }

    /**
     * 电话(传真)号码合法性检测
     */
    public static function isPhone($value)
    {
        return preg_match("/^[\d]{3,4}-[\d]{7,8}$/", $value);
        //return preg_match ( "/^\d{11}$|^\d{3}-\d{7,8}$|^\d{4}-\d{7,8}$/", $tel );
    }

    /**
     * 电话(传真)号码合法性检测
     */
    public static function isQq($value)
    {
        return preg_match("/^[\d]{5,12}$/", $value);
        //return preg_match ( "/^\d{11}$|^\d{3}-\d{7,8}$|^\d{4}-\d{7,8}$/", $tel );
    }

    /**
     * 手机号码合法性检查
     * @param $str
     * @return mixed
     */
    public static function isMobile($str)
    {
        return preg_match("/^(1[3456789])\d{9}$/i", $str);
    }

    /**
     * 身份证号码合法性检测
     * @param $value
     * @return mixed
     */
    public static function isIdCard($value)
    {
        return preg_match("/^(\d{17}[\dx])$/i", $value);
    }

    /**
     * 严格的身份证号码合法性检测(按照身份证生成算法进行检查)
     * @param $value
     * @return bool
     */
    public static function chkIdCard($value)
    {
        if (strlen($value) != 18) {
            return false;
        }
        $wi    = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        $ai    = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $value = strtoupper($value);
        $sigma = '';
        for ($i = 0; $i < 17; $i++) {
            $sigma += ((int)$value{$i}) * $wi[$i];
        }
        $parity_bit = $ai[($sigma % 11)];
        if ($parity_bit != substr($value, -1)) {
            return false;
        }
        return true;
    }

    /**
     * 检测是否包含特殊字符
     */
    public static function chkSpecialWord($value)
    {
        return preg_match('/>|<|,|\[|\]|\{|\}|\?|\/|\+|=|\||\'|\\|\"|:|;|\~|\!|\@|\#|\*|\$|\%|\^|\&|\(|\)|`/i', $value);
    }


    /**
     * 检测一个文件是否存在（可以是本地文件或者是HTTP协议的文件）
     *
     * @param string $inputPath 文件路径（可以是一个URL或者是本地文件路径）
     * @return mixed 返回false文件不存在，返回true文件存在，返回对象说明有错误
     */
    public static function fileExist($inputPath)
    {
        return is_file($inputPath);
    }

    /**
     * 检测一个用户名的合法性
     *
     * @param string $str 需要检查的用户名字符串
     * @param int $chkType 要求用户名的类型，
     * @          1为英文、数字、下划线，2为任意可见字符，3为中文(GBK)、英文、数字、下划线，4为中文(UTF8)、英文、数字，缺省为1
     * @return bool 返回检查结果，合法为true，非法为false
     */
    public static function checkName($str, $chkType = 1)
    {
        switch ($chkType) {
            case 1:
                $result = preg_match("/^[a-zA-Z0-9_]+$/i", $str);
                break;
            case 2:
                $result = preg_match("/^[\w\d]+$/i", $str);
                break;
            case 3:
                $result = preg_match("/^[_a-zA-Z0-9\0x80-\0xff]+$/i", $str);
                break;
            case 4:
                $result = preg_match("/^[_a-zA-Z0-9\u4e00-\u9fa5]+$/i", $str);
                break;
            default:
                $result = preg_match("/^[a-zA-Z0-9_]+$/i", $str);
                break;
        }
        return $result;
    }

    /**
     * 返回加密后的密码
     * @param $pass
     * @param $salt
     * @return string
     */
    public static function password($pass, $salt)
    {
        return md5(md5($pass) . $salt);
    }

    /**
     * 返回相差的时间
     * @param string $time
     * @param false|string $startTime
     * @param string $suffix
     * @return bool|string
     */
    public static function pastTime($time = "", $startTime = '', $suffix = "前")
    {

        if (!$time) {
            return false;
        }
        $time = strtotime($time);

        if (!$startTime) {
            $startTime = date('Y-m-d H:i:s');
        }
        $toTime = strtotime($startTime);

        $time = $toTime - $time;

        $str = "";
        switch ($time) {
            case $time < 60:
                $str = intval($time) . '秒';
                break;
            case $time < 3600:
                $time = $time / 60;
                $str  = intval($time) . '分钟';
                break;
            case $time < 86400:
                $time = $time / 3600;
                $str  = intval($time) . '小时';
                break;
            case $time < 2592000:
                $time = $time / 86400;
                $str  = intval($time) . '天';
                break;
            case $time < 31536000:
                $time = $time / 2592000;
                $str  = intval($time) . '月';
                break;
            default:
                $time = $time / 31536000;
                $str  = intval($time) . '年';
                break;
        }
        $str .= $suffix;
        return $str;
    }

    /**
     * 检查日期是否合法
     * @param $date
     * @return bool
     */
    public static function checkDateTime($date)
    {
        $arr  = date_parse_from_format('Y年n月j日', $date);
        $time = mktime(0, 0, 0, $arr['month'], $arr['day'], $arr['year']);
        if (date("Y年n月j日", $time) == $date) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查时间戳是否合法
     * @param $timeStamp
     * @return bool
     */
    public static function checkTimeStamp($timeStamp)
    {
        if (strtotime(date("Y-m-d H:i:s", $timeStamp)) == $timeStamp) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 简单的str->数组解析
     * 索引数组:"word1,word2,word3"
     * 关联数组:"key1-word1,key2-word2"
     * 注意两种格式不能混用
     * @pparam $strWords
     * @preturn array|null 解析失败返回null
     */
    public static function wordsParse($strWords)
    {
        if (!$strWords || !is_string($strWords)) {
            return null;
        }
        $arr = array_values(array_filter(explode(',', $strWords)));
        if (!$arr) {
            return null;
        } elseif (false === strpos($arr[0], '-')) {
            return $arr;
        }

        $res = [];
        foreach ($arr as $words) {
            if (false === strpos($words, '-')) return null;
            list($key, $value) = explode('-', $words);
            $res[$key] = $value;
        }
        return $res;
    }

    /**
     * 随机浮点数
     * @param int $min
     * @param int $max
     * @param int $decimals 保留小数位数
     * @return float|int
     */
    public static function randFloat($min = 0, $max = 1, $decimals = null)
    {
        $float = $min + mt_rand() / mt_getrandmax() * ($max - $min);
        if (is_null($decimals)) {
            return $float;
        } else {
            return floatval(number_format($float, $decimals));
        }
    }

    /**
     * 上传文件的随机字符串
     * @return string
     */
    public static function uploadRandKeyName()
    {
        return uniqid() . self::randString(6, 3);
    }

    /**
     * 产生随机字串，可用来自动生成密码
     * 默认长度6位 字母和数字混合 支持中文
     * @param string $len 长度
     * @param string $type 字串类型
     * 0 字母 1 数字 其它 混合
     * @param string $addChars 额外字符
     * @return string
     */
    public static function randString($len = 6, $type = '', $addChars = '')
    {
        $str = '';
        switch ($type) {
            case 0:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            case 1:
                $chars = str_repeat('123456789', 3).$addChars;//默认不要0，防止0开始时达不到长度
                break;
            case 2:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
                break;
            case 3:
                $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            case 4:
                $chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借" . $addChars;
                break;
            default :
                // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
                $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
                break;
        }
        if ($len > 10) {//位数过长重复字符串一定次数
            $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
        }
        if ($type != 4) {
            $chars = str_shuffle($chars);
            $str   = substr($chars, 0, $len);
        } else {
            // 中文随机字
            for ($i = 0; $i < $len; $i++) {
                $str .= self::msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1, 'utf-8', false);
            }
        }
        return $str;
    }

    /**
     * 获取需要的字段(去除不必要的字段)
     * @param $arr
     * @param $fields array 或,隔开的字符串
     * @return array
     */
    public static function getArrayOfFields($arr, $fields)
    {
        if (!is_array($fields)) {
            $fields = explode(',', $fields);
        }
        $data = [];
        foreach ($fields as $field) {
            $data[$field] = $arr[$field];
        }
        return $data;
    }

    /**
     * 返回集合中某个字段的值组成的数组
     * @param $collect
     * @param $field
     * @return array
     */
    public static function getCollectFields($collect, $field)
    {
        $aFieldValues = [];
        if ($collect) {
            foreach ($collect as $oneCollect) {
                if (isset($oneCollect->$field)) {
                    $aFieldValues[] = $oneCollect->$field;
                }
            }
        }
        return $aFieldValues;
    }



    /**
     * 获取图片信息
     * @param $img
     * @return array|bool
     */
    public static function getImageInfo($img)
    {
        $imageInfo = getimagesize($img);
        if ($imageInfo !== false) {
            $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
            $imageSize = filesize($img);
            $info      = array(
                "width"  => $imageInfo[0],
                "height" => $imageInfo[1],
                "type"   => $imageType,
                "size"   => $imageSize,
                "mime"   => $imageInfo['mime']
            );
            return $info;
        } else {
            return false;
        }
    }



    /**
     *  转换一个int为byte数组
     * @param $val 需要转换的字符串
     * @return array $byt 目标byte数组
     */
    public static function integerToBytes($val)
    {
        $byt    = array();
        $byt[0] = ($val & 0xff);
        $byt[1] = ($val >> 8 & 0xff);
        $byt[2] = ($val >> 16 & 0xff);
        $byt[3] = ($val >> 24 & 0xff);
        return $byt;
    }

    /**
     * 修正价格显示 小数点后为0则不显示，同时解决浮点数相加结果小数点N位的问题
     * @param $amount
     * @return float
     */
    public static function formatPrice($amount)
    {
//        return floatval(sprintf('%.2f', round($amount, 2)));
        return round($amount, 2);
    }

    /**
     * 金额转化
     * @param $amount
     * @param int $type 1分转化为元，2元转化为分
     * @return false|float|int
     */
    public static function changPrice($amount, $type = 1)
    {
        return $type == 1 ? sprintf("%.2f", round($amount / 100, 2)) : ceil($amount * 100);
    }


    /**
     * 指定超时时间的file_get_contents，防止阻塞
     * @param $url
     * @param int $timeout 超时时间，单位为秒
     * @param int $throwException 是否直接抛出异常
     * @return false|string
     */
    public static function fileGetContentsTimeout($url, $timeout = 1, $throwException = 0)
    {
        $ctx = stream_context_create(array(
                'http' => array(
                    'timeout' => $timeout //设置一个超时时间，单位为秒
                )
            )
        );
        if ($throwException == 0) {
            try {
                return file_get_contents($url, 0, $ctx);
            } catch (\Exception $e) {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 对象转成数组
     * @param $object
     * @return mixed
     */
    public static function objectToArray($object)
    {
        //先编码成json字符串，再解码成数组
        return json_decode(json_encode($object), true);
    }

    /**
     * 获取树状分类返回
     * @param $data
     * @param int $parentId
     * @param array $deleteField 不返回的字段
     * @param $statusField
     * @return array
     */
    public static function getTree($data, $parentId = 0, $deleteField = [], $statusField = null)
    {
        $arr = array();
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $parentId && ($statusField ? $v[$statusField] == 1 : 1)) {
                foreach ($deleteField as $field) {
                    unset($v[$field]);
                }
                //再查找该分类下是否还有子分类
                if (!empty($rel = self::getTree($data, $v['id'], $deleteField))) {
                    $v['children'] = $rel;
                    //统计child
                    $v['child_num'] = count($v['children']);
                }


                //将找到的分类放回该数组中
                $arr[] = $v;
            }
        }
        return $arr;
    }

    public static function getIosAddressTree($data, $parentId = 0, $deleteField = [], $statusField = null)
    {
        $arr = array();
        foreach ($data as $k => $v) {
            $v['code'] = (string)$v['code'];
            if ($v['parent_id'] == $parentId && ($statusField ? $v[$statusField] == 1 : 1)) {
                foreach ($deleteField as $field) {
                    unset($v[$field]);
                }
                //再查找该分类下是否还有子分类
                if (!empty($rel = self::getIosAddressTree($data, $v['code'], $deleteField))) {
                    if ($v['level'] == 1) {
                        $v['cityList'] = $rel;
                    }
                    if ($v['level'] == 2) {
                        $v['areaList'] = $rel;
                    }

                }
                unset($v['level']);
                unset($v['parent_id']);
                //将找到的分类放回该数组中
                $arr[] = $v;
            }
        }
        return $arr;
    }

    //时间格式化（时间戳）
    static function uc_time_ago($ptime)
    {
        date_default_timezone_set('PRC');
        //$ptime = strtotime($ptime);
        $etime = time() - $ptime;
        switch ($etime) {
            case $etime <= 60:
                $msg = '刚刚';
                break;
            case $etime > 60 && $etime <= 60 * 60:
                $msg = floor($etime / 60) . ' 分钟前';
                break;
            case $etime > 60 * 60 && $etime <= 24 * 60 * 60:
                $msg = floor($etime / 3600) . '小时前';
                break;
            default:
                $msg = '1天前';
        }
        return $msg;
    }

    static function createRandCode($len)
    {
        $str = range('A', 'Z');
        unset($str[array_search('O', $str)]);
        $arr = array_merge(range(0, 9), $str);
        shuffle($arr);
        $code    = '';
        $arr_len = count($arr);
        for ($i = 0; $i < $len; $i++) {
            $rand = mt_rand(0, $arr_len - 1);
            $code .= $arr[$rand];
        }
        return $code;
    }

    public static function getPidTree($data, $parentId = 0, $deleteField = [], $statusField = null)
    {
        $arr = array();
        foreach ($data as $k => $v) {
            if ($v['pid'] == $parentId && ($statusField ? $v[$statusField] == 1 : 1)) {
                foreach ($deleteField as $field) {
                    unset($v[$field]);
                }
                //再查找该分类下是否还有子分类
                if (!empty($rel = self::getPidTree($data, $v['id'], $deleteField))) {
                    $v['children'] = $rel;
                    //统计child
//                    $v['child_num'] = count($v['children']);
                }


                //将找到的分类放回该数组中
                $arr[] = $v;
            }
        }
        return $arr;
    }

    public static function spaceHtmlTag($str)
    {
        if (empty($str)) {
            return '';
        }
        $newStr = str_replace('<font ', '<', $str);
        $newStr = str_replace('/font', '/color', $newStr);
        $newStr = str_replace('<p>', '', $newStr);
        $newStr = str_replace('</p>', '', $newStr);
        $newStr = str_replace('</br>', '', $newStr);
        $newStr = str_replace('"#', '#', $newStr);
        $newStr = str_replace('">', '>', $newStr);
        return str_replace('<br>', '', $newStr);
    }

    public static function getMilliSecond()
    {
        list($microsecond, $time) = explode(' ', microtime()); //' '中间是一个空格
        return sprintf('%d', (floatval($microsecond) + floatval($time)) * 1000);
    }

    //小程序调用指定content-type为json
    public static function http_mini_curl($url, $postFields = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        if (is_array($postFields) && 0 < count($postFields)) {
            $header = array("content-type: application/json");
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));
        }
        $reponse = curl_exec($ch);

        if (curl_errno($ch)) {
            throw new Exception(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new Exception($reponse, $httpStatusCode);
            }
        }
        curl_close($ch);
        return json_decode($reponse,true);
    }

    //转换时间为特定格式
    static function dateTimeToUpper($stamp, $type)
    {
        $year = str_split(date('Y', $stamp));
        $month = intval(date('m', $stamp));
        $day = intval(date('d', $stamp));

        $chars = array(
            0 => ['〇', '零'],
            1 => ['一', '壹'],
            2 => ['二', '贰'],
            3 => ['三', '叁'],
            4 => ['四', '肆'],
            5 => ['五', '伍'],
            6 => ['六', '陆'],
            7 => ['七', '柒'],
            8 => ['八', '捌'],
            9 => ['九', '玖'],
            10 => ['十', '拾'],
            11 => ['十一', '拾壹'],
            12 => ['十二', '拾贰'],
            13 => ['十三', '拾叁'],
            14 => ['十四', '拾肆'],
            15 => ['十五', '拾伍'],
            16 => ['十六', '拾陆'],
            17 => ['十七', '拾柒'],
            18 => ['十八', '拾捌'],
            19 => ['十九', '拾玖'],
            20 => ['二十', '贰拾'],
            21 => ['二十一', '贰拾壹'],
            22 => ['二十二', '贰拾贰'],
            23 => ['二十三', '贰拾叁'],
            24 => ['二十四', '贰拾肆'],
            25 => ['二十五', '贰拾伍'],
            26 => ['二十六', '贰拾陆'],
            27 => ['二十七', '贰拾柒'],
            28 => ['二十八', '贰拾捌'],
            29 => ['二十九', '贰拾玖'],
            30 => ['三十', '叁拾'],
            31 => ['三十一', '叁拾壹'],
        );
        $date = '';
        foreach ($year as $y) {
            $date .= $chars[$y][$type];
        }
        $date .= '年';
        $date .= $chars[$month][$type] . '月';
        $date .= $chars[$day][$type] . '日';
        return $date;
    }
}
